//
//  OCUserInfoViewModel.m
//  ocVB
//
//  Created by apple on 2016/10/27.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "OCUserInfoViewModel.h"
#import "OCNetworkingTool.h"
#import "OCUserInfoModel.h"

@interface OCUserInfoViewModel ()

@property(nonatomic,strong)OCUserInfoModel * model;

@property(nonatomic,strong)NSString * filePath;

@end

@implementation OCUserInfoViewModel

+(instancetype)sharedInfoModel{
    static OCUserInfoViewModel * model;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        model = [[OCUserInfoViewModel alloc] init];
        model.filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingString:@"xiaozi.db"];
    });
    return model;

}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.userModel = [self GetData];
    }
    return self;
}

-(void)setAccessToken:(NSString *)accessToken
{
    if ([self.userModel.expires_Date compare:[NSDate date]] == NSOrderedDescending) {
        _accessToken = accessToken;
        self.isLogin = YES;
    }else{
        _accessToken = nil;
        self.isLogin = NO;
    }
}

/**
 保存数据

 @param model 数据
 */
- (void)saveData:(OCUserInfoModel *)model{
    self.model = model;
    [NSKeyedArchiver archiveRootObject:model toFile:self.filePath];
}

/**
 获取存储数据

 @return 数据
 */
- (OCUserInfoModel *)GetData{
    OCUserInfoModel *model = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];
    return model;
}

- (void)getUserAccount:(NSString *)code finish:(void(^)(BOOL))finish{
    [[OCNetworkingTool sharedManager] getUserTocken:code success:^(NSDictionary * response) {
        OCUserInfoModel *model = [OCUserInfoModel yy_modelWithJSON:response];
        [self getUserInfo:model finish:finish];
        
    } failure:^(NSError *error) {
        finish(NO);
        NSLog(@"---%@",error);
    }];

    
}
- (void)getUserInfo:(OCUserInfoModel *)model finish:(void(^)(BOOL))finish{
    [[OCNetworkingTool sharedManager] oauthLoadUserInfo:model success:^(NSDictionary* response) {
        
//        if ([response isMemberOfClass:NSDictionary]) {
            model.screen_name = response[@"screen_name"];
            model.avatar_large = response[@"avatar_large"];
        NSLog(@"model----- %@",model);
        [self saveData:model];
        finish(YES);
    } failure:^(NSError *error) {
        finish(NO);
        NSLog(@"00000失败%@",error);
    }];
    
}

@end
